﻿#include "widget.h"
#include "./ui_widget.h"

#include <QDebug>

using namespace libdaq::device;

Widget::Widget(QWidget *parent)
    : QWidget(parent), ui(new Ui::Widget) {
  ui->setupUi(this);
}

Widget::~Widget() {
  delete ui;
}

void Widget::on_ConnectPushButton_clicked() {

#if defined(USE_RS485) && !defined(USE_TCP_CLIENT) && !defined(USE_MODBUS)
  daq331m.UseSerialBackend(R"(\\.\COM20)", 115200);
#elif defined(USE_TCP_CLIENT) && !defined(USE_RS485) && !defined(USE_MODBUS)
  daq331m_.UseTCPClientBackend("192.168.1.20", 8000);
#elif defined(USE_MODBUS) && !defined(USE_RS485) && !defined(USE_TCP_CLIENT)
  daq331m.UseModbusRTUBackend(R"(\\.\COM20)", 115200, 1);
#endif

  // 初始化一个DAQ设备
  if (!daq331m_.InitializeDevice()) {
    qDebug() << (u8"libdaq初始化设备失败");
  }

  // 连接一个DAQ设备
  if (!daq331m_.ConnectedDevice()) {
    qDebug(u8"libdaq连接设备失败");
  }
}

void Widget::on_StartPWM1PushButton_clicked() {
  auto frequency = ui->PWM1FrequentLineEdit->text().toUInt();
  auto duty = ui->PWM1DutyCycleLineEdit->text().toUInt();

  if (!daq331m_.ConfigPWM(DAQPWMChannel::PWM1, frequency, duty)) {
    qDebug() << u8"libdaq配置PWM1失败";
    return;
  }

  if (!daq331m_.StartPWM(DAQPWMChannel::PWM1)) {
    qDebug() << u8"libdaq开启PWM1失败";
  }
}

void Widget::on_StopPWM1PushButton_clicked() {
  if (!daq331m_.StopPWM(DAQPWMChannel::PWM1)) {
    qDebug() << u8"libdaq关闭PWM1失败";
  }
}

void Widget::on_StartPWM2PushButton_clicked() {
  auto frequency = ui->PWM2FrequentLineEdit->text().toUInt();
  auto duty = ui->PWM2DutyCycleLineEdit->text().toUInt();

  if (!daq331m_.ConfigPWM(DAQPWMChannel::PWM2, frequency, duty)) {
    qDebug() << u8"libdaq配置PWM2失败";
    return;
  }

  if (!daq331m_.StartPWM(DAQPWMChannel::PWM2)) {
    qDebug() << u8"libdaq开启PWM2失败";
  }
}

void Widget::on_StopPWM2PushButton_clicked() {
  if (!daq331m_.StopPWM(DAQPWMChannel::PWM2)) {
    qDebug() << u8"libdaq关闭PWM2失败";
  }
}
